using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 盘点类型查询命令处理器（查询所有盘点类型列表）
    /// </summary>
    public class InventoryTypeQueryCommandHandler : IRequestHandler<InventoryTypeQueryCommand, ApiResult<List<InventoryTypeInfoResultDTO>>>
    {
        private readonly IBaseRepository<InventoryTypeInfo> inventoryTypeRepository;

        /// <summary>
        /// 构造函数，注入盘点类型仓储
        /// </summary>
        public InventoryTypeQueryCommandHandler(IBaseRepository<InventoryTypeInfo> inventoryTypeRepository)
        {
            this.inventoryTypeRepository = inventoryTypeRepository;
        }

        /// <summary>
        /// 处理盘点类型查询命令（返回所有盘点类型列表）
        /// </summary>
        public async Task<ApiResult<List<InventoryTypeInfoResultDTO>>> Handle(InventoryTypeQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询所有盘点类型（按ID排序）
                var inventoryTypes = inventoryTypeRepository.GetAll()
                    .OrderBy(x => x.InventoryTypeId)
                    .Select(x => new InventoryTypeInfoResultDTO
                    {
                        InventoryTypeId = x.InventoryTypeId,
                        InventoryTypeName = x.InventoryTypeName
                    })
                    .ToList();

                return new ApiResult<List<InventoryTypeInfoResultDTO>>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询盘点类型列表成功",
                    Data = inventoryTypes
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<List<InventoryTypeInfoResultDTO>>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询盘点类型列表异常：{ex.Message}",
                    Data = new List<InventoryTypeInfoResultDTO>()
                };
            }
        }
    }
}

